﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TravelLink.DAL;
using TravelLink.Common;
using System.Web;

namespace TravelLink.WebModel {
    public class UserController {
        public static UserController GetInstance() {
            return new UserController();
        }


        public bool Register(TL_User userEntity) {

            if (userEntity != null) {
                var db = TravelLink.DAL.DataContextFactory.Create();
                if (db.TL_User.Where(u => u.Email.ToUpper() == userEntity.Email.ToUpper()).FirstOrDefault() != null) {
                    return false;
                }

                db.TL_User.InsertOnSubmit(userEntity);
                db.SubmitChanges();

                OnlineUserInfo userInfo = new OnlineUserInfo();
                userInfo.LoginTime = DateTime.Now;
                userInfo.DBUser = userEntity;
                UserStoreFacade.Login(userInfo);


                try {
                    MailSender.SendMailByRegisterValidation(userEntity.UserCode, userEntity.Email);
                }
                catch (Exception ex) {
                    HttpContext.Current.Response.Write(ex.ToString());
                }
                return true;
            }
            return false;
        }

        public string Login(string userName, string password) {
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) {
                var db = TravelLink.DAL.DataContextFactory.Create();
                var user = db.TL_User.Where(u => u.Email.ToUpper() == userName.ToUpper() && u.Password == password)
                    .FirstOrDefault();
                if (user != null) {
                    OnlineUserInfo userInfo = new OnlineUserInfo();
                    userInfo.LoginTime = DateTime.Now;
                    userInfo.DBUser = user;
                    UserStoreFacade.Login(userInfo);
                    return "OK";
                }
                else {
                    return "该用户不存在";
                }
            }
            else {
                return "请输入登陆所需要的信息.";
            }
        }

        public void Logout() {
            UserStoreFacade.Logout();
        }
    }
}
